﻿@page "/tests/datagrid/validations"
<Row>
    <Column>
        <Card Margin="Margin.Is4.OnY">
            <CardHeader>
                <CardTitle>Datagrid: Validations</CardTitle>
            </CardHeader>
            <CardBody>
                <Paragraph>Try editing or creating a new item and watch validations working!</Paragraph>
                <Divider DividerType="DividerType.TextContent" Text="Demo validators"></Divider>
                <Paragraph>
                    <Badge Color="Color.Primary">
                        Annotations:
                    </Badge>
                    First Name, LastName and EmailAddress fields have the <code>[Required]</code> annotation. EmailAddress field additionally has the <code>[EmailAddress]</code> annotation.
                </Paragraph>
                <Paragraph>
                    <Badge Color="Color.Info">
                        Validator:
                    </Badge>
                    The City field has an inbuilt Validator provided by Blazorise that checks if the input has only UpperCase letters.
                </Paragraph>
                <Paragraph>
                    <Badge Color="Color.Info">
                        Validator:
                    </Badge>
                    The Gender field uses the Validator to provide a custom validation checking whether the value provided is within the expected "M"/"F"/"D" values.
                </Paragraph>
                <Paragraph>
                    <Badge Color="Color.Info">
                        Validator:
                    </Badge>
                    The Active field uses the Validator to provide a custom validation checking whether the value is set to true.
                </Paragraph>
                <Paragraph>
                    <Badge Color="Color.Info">
                        Validator:
                    </Badge>
                    The Zip field has a ValidationPattern that checks whether a zip follows a format like 12345-6789.
                </Paragraph>
            </CardBody>
            <CardBody>
                <Field>
                    <FieldLabel>
                        Edit Mode
                    </FieldLabel>
                    <FieldBody>
                        <Select @bind-SelectedValue="@editMode">
                            <SelectItem Value="DataGridEditMode.Form">Form</SelectItem>
                            <SelectItem Value="DataGridEditMode.Inline">Inline</SelectItem>
                            <SelectItem Value="DataGridEditMode.Popup">Popup</SelectItem>
                        </Select>
                    </FieldBody>
                </Field>
                <DataGrid TItem="Employee"
                          Data="inMemoryData"
                          Responsive
                          ShowPager
                          ShowPageSizes
                          @bind-SelectedRow="@selectedEmployee"
                          Editable
                          EditMode="editMode"
                          UseValidation
                          ValidationsSummaryLabel="The following validation errors have occurred..."
                          ShowValidationsSummary>
                    <DataGridColumns>
                        <DataGridCommandColumn TItem="Employee"></DataGridCommandColumn>
                        <DataGridColumn TextAlignment="TextAlignment.Center" TItem="Employee" Field="@nameof( Employee.Id )" Caption="#" Width="60px" />
                        <DataGridColumn TItem="Employee" Field="@nameof( Employee.FirstName )" Caption="First Name" Editable />
                        <DataGridColumn TItem="Employee" Field="@nameof( Employee.LastName )" Caption="Last Name" Editable />
                        <DataGridColumn TItem="Employee" Field="@nameof( Employee.Email )" Caption="Email" Editable />
                        <DataGridColumn TItem="Employee" Field="@nameof( Employee.City )" Caption="City" AsyncValidator="@IsNotEmptyAsync" Editable>
                            <CaptionTemplate>
                                <Icon Name="IconName.City" /> @context.Caption
                            </CaptionTemplate>
                        </DataGridColumn>
                        <DataGridColumn TItem="Employee" Field="@nameof( Employee.Zip )" ValidationPattern="^\d{5}(?:[-]\d{4})$" Caption="Zip">
                        </DataGridColumn>
                        <DataGridDateColumn TItem="Employee" Field="@nameof( Employee.DateOfBirth )" DisplayFormat="{0:dd.MM.yyyy}" Caption="Date Of Birth" Editable />
                        <DataGridNumericColumn TItem="Employee" Field="@nameof( Employee.Childrens )" Caption="Childrens" Editable Filterable="false" />
                        <DataGridSelectColumn Validator="@ValidateGender" TItem="Employee" Field="@nameof( Employee.Gender )" Caption="Gender" Editable Data="EmployeeData.Genders" ValueField="(x) => ((Gender)x).Code" TextField="(x) => ((Gender)x).Description" />
                        <DataGridColumn TItem="Employee" Field="@nameof( Employee.Salary )" Caption="Salary" Editable Width="140px" DisplayFormat="{0:C}" DisplayFormatProvider="@System.Globalization.CultureInfo.GetCultureInfo("fr-FR")" TextAlignment="TextAlignment.End">
                        </DataGridColumn>
                        <DataGridCheckColumn TItem="Employee" Field="@nameof(Employee.IsActive)" Caption="Active" Editable Filterable="false" Validator="@ValidateCheck">
                            <DisplayTemplate>
                                <Check TValue="bool" Checked="context.IsActive" Disabled ReadOnly />
                            </DisplayTemplate>
                        </DataGridCheckColumn>
                    </DataGridColumns>
                </DataGrid>
            </CardBody>
        </Card>
    </Column>
</Row>

@code {


    [Inject] EmployeeData EmployeeData { get; set; }

    private List<Employee> inMemoryData;
    private Employee selectedEmployee;
    private DataGridEditMode editMode = DataGridEditMode.Popup;

    protected override async Task OnInitializedAsync()
    {
        inMemoryData = ( await EmployeeData.GetDataAsync().ConfigureAwait( false ) ).Take( 25 ).ToList();
        await base.OnInitializedAsync();
    }
    Random random = new();

    async Task IsNotEmptyAsync( ValidatorEventArgs e, System.Threading.CancellationToken cancellationToken )
    {
        cancellationToken.ThrowIfCancellationRequested();

        await Task.Delay( random.Next( 1300 ) );

        e.Status = string.IsNullOrEmpty( Convert.ToString( e.Value ) )
            ? ValidationStatus.Error
            : ValidationStatus.Success;

        if ( e.Status == ValidationStatus.Error )
            e.ErrorText = "City is not valid";
    }

    void ValidateCheck( ValidatorEventArgs e )
    {
        e.ErrorText = $"Field Active must be true";
        var value = e.Value?.ToString();
        e.Status = bool.TryParse( value, out bool result ) && result
                    ? ValidationStatus.Success
                    : ValidationStatus.Error;

    }

    void ValidateGender( ValidatorEventArgs e )
    {
        var validValues = new[] { "M", "F", "D" };
        e.ErrorText = $"Gender must be: {string.Join( ", ", validValues )} ";
        var value = e.Value?.ToString();
        e.Status = validValues.Contains( value )
                    ? ValidationStatus.Success
                    : ValidationStatus.Error;

    }
}